package com.tree.common.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;

/**
 * @ClassName com.demo.common.util
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-05-26 21:25
 * @Version 1.0
 */
public class AESUtil {
    public static final String KEY_ALGORITHM = "AES";
    public static final String CHARTSET = "UTF-8";

    public static byte[] initKey(String password) throws Exception{
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes());
        keyGenerator.init(128,random);
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }

    public static Key toKey(byte[] key){
        SecretKeySpec secretKeySpec = new SecretKeySpec(key,KEY_ALGORITHM);
        return secretKeySpec;
    }

    public static byte[] encrypt(String content,String password) throws Exception{
        byte[] keyByte = initKey(password);
        Key key = toKey(keyByte);

        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        byte[] byteContent = content.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE,key);
        return cipher.doFinal(byteContent);
    }

    public static String encryptStr(String content,String password) throws Exception{
        return Base64.encodeBase64String(encrypt(content,password));
    }

    public static byte[] decrpt(byte[] content, String password) throws Exception{
        byte[] keyByte = initKey(password);
        Key key = toKey(keyByte);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,key);
        return cipher.doFinal(content);
    }

    public static String decrptStr(String content,String password) throws Exception{
        return new String(decrpt(Base64.decodeBase64(content),password));
    }

    public static void main(String[] args) throws Exception{
        String content = "boardata";
        String password = "zaq1@WSX";
        //加密
        System.err.println("加密前："+content);
        String encrptStr = encryptStr(content,password);
        System.err.println("加密后："+encrptStr);

        //解密
        String decrptStr = decrptStr(encrptStr,password);
        System.err.println("解密后：");
        System.err.println(decrptStr);
    }



}
